package com.lvmama.common.utils;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json转换工具类
 *
 * @author caoyong
 * @since 2018年1月29日 下午12:54:09
 */
@Slf4j
public class JSONConversionUtil {

    /**
     * 对象转string
     *
     * @param o 对象
     * @return 对象的json字符串
     */
    public static String objToString(Object o) {
        log.info("objToString start.");
        ObjectMapper om = new ObjectMapper();
        //非空
        om.setSerializationInclusion(Include.NON_NULL);
        StringWriter w = new StringWriter();
        try {
            om.writeValue(w, o);
            return w.toString();
        } catch (Exception e) {
            log.error("objToString error:" + e.getMessage(), e);
        }
        log.info("objToString end.");
        return null;
    }

    /**
     * json string 转对象
     *
     * @param content 对象json字符串
     * @param cls     类型
     * @return 对象
     */
    public static <T> T stringToObj(String content, Class<T> cls) {
        log.info("stringToObj start.");
        ObjectMapper om = new ObjectMapper();
        try {
            return om.readValue(content, cls);
        } catch (Exception e) {
            log.error("objToString error:" + e.getMessage(), e);
        }
        log.info("stringToObj end.");
        return null;
    }

    /**
     * 对象转换为List集合
     *
     * @param content 字符串
     * @param clazz   类
     * @param <T>     类型
     * @return List集合
     */
    public static <T> List<T> stringToList(String content, Class<T> clazz) {
        log.info("stringToList start, content:{}"+ content);
        List<T> list = null;
        try {
            JSONArray json = JSONArray.parseArray(content);
            T t;
            list = new ArrayList<>();
            for (Object obj : json) {
                JSONObject jsonObject = (JSONObject) obj;
                t = JSONObject.toJavaObject(jsonObject, clazz);
                list.add(t);
            }
        } catch (Exception e) {
            log.error("stringToList error:" + e.getMessage(), e);
        }
        log.info("stringToList end.");
        return list;
    }
}
